#include "server.h"
#include "common/threadpool.h"
#include "connection.h"
#include "common/log.h"


namespace evm {
    namespace http {

        using namespace common;

        HTTPServer::HTTPServer(const string &host, uint16_t port, size_t concurrency, EventLoop *loop)
                : TCPServer(host, port, loop), timer_queue_(KEEPALIVE_TIMEOUT) {

            loop_->add_timer(1, [this](size_t) {
                timer_queue_.get();
                return EV_PERIODIC;
            });


            pool_ = new ThreadPool(concurrency);

            set_handler([this](int conn_fd, EventLoop*) {
                // Every http connection will delete itself at the end of its life cycle
                auto conn = new HTTPConnection(conn_fd, this);
                conn->start();
            });
        }

        HTTPServer::~HTTPServer() {
            delete pool_;
        }

        void HTTPServer::start() {
            pool_->start();

            TCPServer::start();

            pool_->join();
        }

        void HTTPServer::stop() {
            TCPServer::stop();
            pool_->stop();
        }

        void HTTPServer::handle(Request &request, Response &response) {
            log_info("handle url: ", request.str());
            response = router_.route(request.path, request);
            log_info("reponse.body size: ", response.body.size());
        }

    }
}
